/**
 * @swagger
 * /api/high-goods/basic-stats:
 *   get:
 *     tags:
 *       - 高价值品统计
 *     summary: 获取高价值品基础统计数据
 *     description: 获取高价值品总数量、总金额、单位数量等基础统计数据，支持时间筛选
 *     parameters:
 *       - in: query
 *         name: startTime
 *         schema:
 *           type: string
 *           format: date
 *         description: 开始时间 (YYYY-MM-DD)
 *         example: "2023-01-01"
 *       - in: query
 *         name: endTime
 *         schema:
 *           type: string
 *           format: date
 *         description: 结束时间 (YYYY-MM-DD)
 *         example: "2023-12-31"
 *     responses:
 *       200:
 *         description: 成功获取基础统计数据
 *         content:
 *           application/json:
 *             schema:
 *               type: object
 *               properties:
 *                 code:
                   type: integer
                   example: 200
                   description: 响应状态码
                 message:
                   type: string
                   example: "基础统计获取成功"
                   description: 响应消息
 *                 data:
                   type: object
                   properties:
 *                     overview:
                       type: object
                       properties:
                         totalRecords:
                           type: integer
                           description: 总记录数
                           example: 1250
                         totalQuantity:
                           type: integer
                           description: 总数量
                           example: 5000
                         totalAmount:
                           type: string
                           description: 总金额
                           example: "125000.50"
                         totalUnits:
                           type: integer
                           description: 总单位数
                           example: 45
                         totalTimePoints:
                           type: integer
                           description: 总时间点数
                           example: 48
                         dataTimeRange:
                           type: object
                           properties:
                             earliest:
                               type: string
                               description: 最早时间
                               example: "2023-01-01"
                             latest:
                               type: string
                               description: 最晚时间
                               example: "2023-12-31"
 *                     averages:
                       type: object
                       properties:
                         avgQuantityPerRecord:
                           type: string
                           description: 每记录平均数量
                           example: "4.00"
                         avgAmountPerRecord:
                           type: string
                           description: 每记录平均金额
                           example: "100.00"
                         avgQuantityPerUnit:
                           type: string
                           description: 每单位平均数量
                           example: "111.11"
                         avgAmountPerUnit:
                           type: string
                           description: 每单位平均金额
                           example: "2777.79"
                         avgRecordsPerUnit:
                           type: string
                           description: 每单位平均记录数
                           example: "27.78"
                         avgValuePerItem:
                           type: string
                           description: 每项平均价值
                           example: "25.00"
 *                     distribution:
                       type: object
                       properties:
                         quantityRange:
                           type: object
                           properties:
                             min:
                               type: integer
                               description: 最小数量
                               example: 1
                             max:
                               type: integer
                               description: 最大数量
                               example: 500
                         amountRange:
                           type: object
                           properties:
                             min:
                               type: string
                               description: 最小金额
                               example: "100.00"
                             max:
                               type: string
                               description: 最大金额
                               example: "50000.00"
                         dataAvailability:
                           type: object
                           properties:
                             recordsWithQuantity:
                               type: integer
                               description: 有数量数据的记录数
                               example: 1200
                             recordsWithAmount:
                               type: integer
                               description: 有金额数据的记录数
                               example: 1180
                             quantityDataRatio:
                               type: string
                               description: 数量数据完整率(%)
                               example: "96.00"
                             amountDataRatio:
                               type: string
                               description: 金额数据完整率(%)
                               example: "94.40"
 *                     timeStatistics:
                       type: object
                       properties:
                         totalTimePoints:
                           type: integer
                           description: 总时间点数
                           example: 48
                         totalYears:
                           type: integer
                           description: 总年数
                           example: 4
                         totalMonths:
                           type: integer
                           description: 总月数
                           example: 12
                         avgQuantityPerTime:
                           type: string
                           description: 每时间点平均数量
                           example: "104.17"
                         avgAmountPerTime:
                           type: string
                           description: 每时间点平均金额
                           example: "2604.18"
                         timeDataRatio:
                           type: string
                           description: 时间数据完整率(%)
                           example: "100.00"
 *                     dataIntegrity:
                       type: object
                       properties:
                         totalRecords:
                           type: integer
                           description: 总记录数
                           example: 1250
                         completeness:
                           type: object
                           properties:
                             hasId:
                               type: integer
                               description: 有ID的记录数
                               example: 1250
                             hasTime:
                               type: integer
                               description: 有时间的记录数
                               example: 1250
                             hasUnit:
                               type: integer
                               description: 有单位的记录数
                               example: 1245
                             hasQuantity:
                               type: integer
                               description: 有数量的记录数
                               example: 1200
                             hasAmount:
                               type: integer
                               description: 有金额的记录数
                               example: 1180
                         ratios:
                           type: object
                           properties:
                             idRatio:
                               type: string
                               description: ID完整率(%)
                               example: "100.00"
                             timeRatio:
                               type: string
                               description: 时间完整率(%)
                               example: "100.00"
                             unitRatio:
                               type: string
                               description: 单位完整率(%)
                               example: "99.60"
                             quantityRatio:
                               type: string
                               description: 数量完整率(%)
                               example: "96.00"
                             amountRatio:
                               type: string
                               description: 金额完整率(%)
                               example: "94.40"

 *       500:
 *         description: 服务器内部错误
 */
const { query } = require('../../../lib/db');
const { success, error: createError, handleResponse } = require('../../../lib/response');
const { withCors } = require('../../../lib/cors');

/**
 * 高价值品基础统计接口处理函数
 * @param {Object} req - 请求对象
 * @param {Object} req.query - 查询参数
 * @param {string} [req.query.startTime] - 开始时间
 * @param {string} [req.query.endTime] - 结束时间
 * @param {Object} res - 响应对象
 * @returns {Promise<Object>} 返回基础统计数据
 */
async function handler(req, res) {
  
  try {
    // 获取时间筛选参数
    const { startTime, endTime } = req.query;
    
    // 构建时间筛选条件
    let timeCondition = '';
    if (startTime || endTime) {
      const conditions = [];
      if (startTime) conditions.push(`TJSJ >= '${startTime}'`);
      if (endTime) conditions.push(`TJSJ <= '${endTime}'`);
      timeCondition = ` AND ${conditions.join(' AND ')}`;
    }
    
    // 基础统计查询
    const basicQuery = `
      SELECT 
        COUNT(*) as totalRecords,
        SUM(COALESCE(GJZSL, 0)) as totalQuantity,
        SUM(COALESCE(GJZJE, 0)) as totalAmount,
        COUNT(DISTINCT DWMC) as totalUnits,
        AVG(COALESCE(GJZSL, 0)) as avgQuantityPerRecord,
        AVG(COALESCE(GJZJE, 0)) as avgAmountPerRecord,
        COUNT(DISTINCT TJSJ) as totalTimePoints,
        MIN(TJSJ) as earliestTime,
        MAX(TJSJ) as latestTime
      FROM wd_zcgk_gjzzcdwfb
      WHERE 1=1${timeCondition}
    `;

    const basicResult = await query(basicQuery);
    const data = basicResult[0];

    // 数量和金额分布统计
    const distributionQuery = `
      SELECT 
        MIN(GJZSL) as minQuantity,
        MAX(GJZSL) as maxQuantity,
        MIN(GJZJE) as minAmount,
        MAX(GJZJE) as maxAmount,
        COUNT(CASE WHEN GJZSL > 0 THEN 1 END) as recordsWithQuantity,
        COUNT(CASE WHEN GJZJE > 0 THEN 1 END) as recordsWithAmount,
        SUM(COALESCE(GJZJE, 0)) / NULLIF(SUM(COALESCE(GJZSL, 0)), 0) as avgValuePerItem
      FROM wd_zcgk_gjzzcdwfb
      WHERE 1=1${timeCondition}
    `;

    const distributionResult = await query(distributionQuery);
    const distributionData = distributionResult[0];

    // 单位级别统计
    const unitStatsQuery = `
      SELECT 
        COUNT(*) as totalUnits,
        AVG(unit_quantity) as avgQuantityPerUnit,
        AVG(unit_amount) as avgAmountPerUnit,
        AVG(unit_records) as avgRecordsPerUnit
      FROM (
        SELECT 
          DWMC,
          SUM(COALESCE(GJZSL, 0)) as unit_quantity,
          SUM(COALESCE(GJZJE, 0)) as unit_amount,
          COUNT(*) as unit_records
        FROM wd_zcgk_gjzzcdwfb
        WHERE 1=1${timeCondition}
        GROUP BY DWMC
      ) unit_stats
    `;

    const unitStatsResult = await query(unitStatsQuery);
    const unitStatsData = unitStatsResult[0];

    // 时间分布统计
    const timeStatsQuery = `
      SELECT 
        COUNT(DISTINCT TJSJ) as totalTimePoints,
        COUNT(DISTINCT SUBSTRING(TJSJ, 1, 4)) as totalYears,
        COUNT(DISTINCT SUBSTRING(TJSJ, 1, 7)) as totalMonths,
        SUM(COALESCE(GJZSL, 0)) / COUNT(DISTINCT TJSJ) as avgQuantityPerTime,
        SUM(COALESCE(GJZJE, 0)) / COUNT(DISTINCT TJSJ) as avgAmountPerTime
      FROM wd_zcgk_gjzzcdwfb
      WHERE TJSJ IS NOT NULL AND TJSJ != ''${timeCondition}
    `;

    const timeStatsResult = await query(timeStatsQuery);
    const timeStatsData = timeStatsResult[0];

    // 数据完整性检查
    const integrityQuery = `
      SELECT 
        COUNT(*) as totalRecords,
        COUNT(CASE WHEN ID IS NOT NULL AND ID != '' THEN 1 END) as hasId,
        COUNT(CASE WHEN TJSJ IS NOT NULL AND TJSJ != '' THEN 1 END) as hasTime,
        COUNT(CASE WHEN DWMC IS NOT NULL AND DWMC != '' THEN 1 END) as hasUnit,
        COUNT(CASE WHEN GJZSL IS NOT NULL AND GJZSL > 0 THEN 1 END) as hasQuantity,
        COUNT(CASE WHEN GJZJE IS NOT NULL AND GJZJE > 0 THEN 1 END) as hasAmount
      FROM wd_zcgk_gjzzcdwfb
      WHERE 1=1${timeCondition}
    `;

    const integrityResult = await query(integrityQuery);
    const integrityData = integrityResult[0];

    const responseData = {
      overview: {
        totalRecords: parseInt(data.totalRecords),
        totalQuantity: parseInt(data.totalQuantity || 0),
        totalAmount: parseFloat(data.totalAmount || 0).toFixed(2),
        totalUnits: parseInt(data.totalUnits || 0),
        totalTimePoints: parseInt(data.totalTimePoints || 0),
        dataTimeRange: {
          earliest: data.earliestTime || '未知',
          latest: data.latestTime || '未知'
        }
      },
      averages: {
        avgQuantityPerRecord: parseFloat(data.avgQuantityPerRecord || 0).toFixed(2),
        avgAmountPerRecord: parseFloat(data.avgAmountPerRecord || 0).toFixed(2),
        avgQuantityPerUnit: parseFloat(unitStatsData.avgQuantityPerUnit || 0).toFixed(2),
        avgAmountPerUnit: parseFloat(unitStatsData.avgAmountPerUnit || 0).toFixed(2),
        avgRecordsPerUnit: parseFloat(unitStatsData.avgRecordsPerUnit || 0).toFixed(2),
        avgValuePerItem: parseFloat(distributionData.avgValuePerItem || 0).toFixed(2)
      },
      distribution: {
        quantityRange: {
          min: parseInt(distributionData.minQuantity || 0),
          max: parseInt(distributionData.maxQuantity || 0)
        },
        amountRange: {
          min: parseFloat(distributionData.minAmount || 0).toFixed(2),
          max: parseFloat(distributionData.maxAmount || 0).toFixed(2)
        },
        dataAvailability: {
          recordsWithQuantity: parseInt(distributionData.recordsWithQuantity || 0),
          recordsWithAmount: parseInt(distributionData.recordsWithAmount || 0),
          quantityDataRatio: ((parseInt(distributionData.recordsWithQuantity || 0) / parseInt(data.totalRecords || 1)) * 100).toFixed(2),
          amountDataRatio: ((parseInt(distributionData.recordsWithAmount || 0) / parseInt(data.totalRecords || 1)) * 100).toFixed(2)
        }
      },
      timeStatistics: {
        totalTimePoints: parseInt(timeStatsData.totalTimePoints || 0),
        totalYears: parseInt(timeStatsData.totalYears || 0),
        totalMonths: parseInt(timeStatsData.totalMonths || 0),
        avgQuantityPerTime: parseFloat(timeStatsData.avgQuantityPerTime || 0).toFixed(2),
        avgAmountPerTime: parseFloat(timeStatsData.avgAmountPerTime || 0).toFixed(2),
        timeDataRatio: ((parseInt(timeStatsData.totalTimePoints || 0) / parseInt(data.totalRecords || 1)) * 100).toFixed(2)
      },
      dataIntegrity: {
        totalRecords: parseInt(integrityData.totalRecords),
        completeness: {
          hasId: parseInt(integrityData.hasId || 0),
          hasTime: parseInt(integrityData.hasTime || 0),
          hasUnit: parseInt(integrityData.hasUnit || 0),
          hasQuantity: parseInt(integrityData.hasQuantity || 0),
          hasAmount: parseInt(integrityData.hasAmount || 0)
        },
        ratios: {
          idRatio: ((parseInt(integrityData.hasId || 0) / parseInt(integrityData.totalRecords || 1)) * 100).toFixed(2),
          timeRatio: ((parseInt(integrityData.hasTime || 0) / parseInt(integrityData.totalRecords || 1)) * 100).toFixed(2),
          unitRatio: ((parseInt(integrityData.hasUnit || 0) / parseInt(integrityData.totalRecords || 1)) * 100).toFixed(2),
          quantityRatio: ((parseInt(integrityData.hasQuantity || 0) / parseInt(integrityData.totalRecords || 1)) * 100).toFixed(2),
          amountRatio: ((parseInt(integrityData.hasAmount || 0) / parseInt(integrityData.totalRecords || 1)) * 100).toFixed(2)
        }
      },

    };

    return handleResponse(res, success(responseData, "高价值品基础统计获取成功"));
    
  } catch (err) {
    console.error(arguments[1], err);
    return handleResponse(res, createError("获取高价值品基础统计失败", 500));
  }
}

export default withCors(handler, ['GET']);